package com.demo.rabbitmq.demo02;

import com.demo.rabbitmq.contanst.Constant;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

public class WorkQueueSend {

    public static void execute(String host, String username, String password, int id) {
        // 配置连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置参数
        factory.setHost(host);
        factory.setUsername(username);
        factory.setPassword(password);

        //
        Connection connection;
        Channel channel = null;

        try {
            // 建立TCP连接
            connection = factory.newConnection();
            // 在TCP连接基础上创建信道
            channel = connection.createChannel();
            // 声明一个队列
            channel.queueDeclare(Constant.TASK_QUEUE_NAME, true, false, false, null);

            String message = "WorkQueueMessageBody-" + id + "-[" + LocalDateTime.now() + "]";
            // 发送一个持久化消息
            channel.basicPublish("", Constant.TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                message.getBytes("UTF-8"));
            System.out.println("WorkQueueSend-" + id + " Send Message...");
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            try {
                assert channel != null;
                channel.close();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }

    }
}
